package xuegao.study.mall.web.es.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import xuegao.study.mall.common.api.CommonPage;
import xuegao.study.mall.common.api.CommonResult;
import xuegao.study.mall.web.es.domain.EsProduct;
import xuegao.study.mall.web.es.service.EsProductService;

import java.util.List;

@RestController
@RequestMapping("/esProduct")
public class EsProductController {

    @Autowired
    private EsProductService esProductService;

    @ApiOperation("导入所有数据库中商品到es")
    @PostMapping(value = "/importAll")
    public CommonResult<Integer> importAllList() {
        int count = esProductService.importAll();
        return CommonResult.success(count);
    }

    @ApiOperation("根据id删除商品")
    @GetMapping(value = "/delete/{id}")
    public CommonResult<Object> delete(@PathVariable Long id) {
        esProductService.delete(id);
        return CommonResult.success(null);
    }

    @ApiOperation("根据id批量删除商品")
    @PostMapping(value = "/delete/batch")
    public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) {
        esProductService.delete(ids);
        return CommonResult.success(null);
    }


    @ApiOperation("根据id创建商品")
    @PostMapping(value = "/create/{id}")
    public CommonResult<EsProduct> create(@PathVariable Long id) {
        EsProduct esProduct = esProductService.create(id);
        if (esProduct != null) {
            return CommonResult.success(esProduct);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("简单搜索")
    @GetMapping(value = "/search/simple")
    public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword,
                                                      @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                      @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        Page<EsProduct> esProductPage = esProductService.search(keyword, pageNum, pageSize);
        List<EsProduct> content = esProductPage.getContent();
        long totalElements = esProductPage.getTotalElements();
        int totalPages = esProductPage.getTotalPages();
        CommonPage<EsProduct> commonPage = new CommonPage<EsProduct>();
        commonPage.setTotalPage(totalPages);
        commonPage.setPageNum(pageNum);
        commonPage.setPageSize(pageSize);
        commonPage.setList(content);
        commonPage.setTotal((int)totalElements);
        return CommonResult.success(commonPage);
    }

}
